const http = require('http')
const os = require("os")
const { time } = require('./utils')
const { name } = require('./name')
const fs = require('fs');
const path = require('path')

//创建web服务器
const server = http.createServer()
var data, info;
var pv, uv,dif;
server.on('request', (request, response) => {
var arr = [],ipList=[],bro=[]
    const ip = request.socket.remoteAddress
    if (request.url !== '/favicon.ico') {
        data = `${ip},${request.method},${request.url},${time()},${request.headers['user-agent']}${os.EOL}`
        // console.log(data)
        // console.log(request.headers);
        fs.appendFile(path.resolve(`data/${name()}.txt`), data, (e, data) => {
            info = fs.readFileSync(path.resolve(`data/${name()}.txt`), 'utf-8')
            //    console.log(info);
            var a = info.split("\r\n")
            a.pop()
            for (var i = 0; i < a.length; i++) {
                arr.push(a[i].split(",")[0])
                bro.push(a[i].split(",")[4])
            }
            ipList=Array.from(new Set(arr))    
            bro=Array.from(new Set(bro))    
            pv=arr.length+1; dif=ipList.length;uv=bro.length
            console.log(arr);
        })

    }
   
    // response.setHeader('Content-Type','text/plain;charset=utf-8')
    // response.setHeader('Content-Type','text/html;charset=utf-8')
    response.setHeader('Content-Type', 'application/json;charset=utf-8')

    // let a=info.split("/r/n")

    // response.end('你好啊')
    // response.end('<h3></h3>')
    response.end(JSON.stringify({ 'pv': pv, name: '张三','不同ip': dif,'uv':uv}))


})
server.listen(3000, '0.0.0.0', () => {
    console.log('服务器启动 http://127.0.0.1:3000');
})